import React, { FC, useState } from 'react'
import './style.scss'
import {
  Table,
  message,
  Tag,
  Space,
  Form,
  Input,
  Button,
  Drawer,
  Popconfirm,
} from 'antd'
import type { ColumnsType } from 'antd/lib/table'
import axios from 'axios'

type ArticleItemType = {
  author: string
  createTime: string
  content: string
  id?: number
  title: string
  key?: string | number
}

interface ArticleProps {
  tableList: ArticleItemType[]
  toParent?: () => void
}

const ArticlePage: FC<ArticleProps> = (props) => {
  const { tableList, toParent } = props
  const [visible, setVisible] = useState(false)

  const [drawerTile, setDrawerTitle] = useState<string>('')

  const [record, setRecord] = useState<ArticleItemType | null>(null)

  const [form] = Form.useForm()

  const columns: ColumnsType<ArticleItemType> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
    },
    {
      title: '创作时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              console.log('record:', record)
              setRecord({ ...record })
              setDrawerTitle('编辑')
              showDrawer()
              form.setFieldsValue({ ...record })
            }}
          >
            编辑
          </a>
          <Popconfirm
            title="确定删除吗?"
            onConfirm={(res) => {
              if (record.id) {
                deleteBlogsItem({ id: record.id })
              }
            }}
            onCancel={(res) => {
              console.log('cancle', res)
            }}
            okText="Yes"
            cancelText="No"
          >
            <a href="#">删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  const showDrawer = () => {
    setVisible(true)
  }

  const onClose = () => {
    setVisible(false)
  }

  const onFinish = async (values: any) => {
    console.log('Success:', values)
    if (drawerTile === '添加') {
      addBlogsItem(values)
    } else {
      updateBlogsItem(values)
    }
    setVisible(false)
  }

  const deleteBlogsItem = async ({ id }: { id: number }) => {
    console.log('id:', id)
    // ts 断言 => 我现在断言 axios是一个any
    const res = await (axios as any).delete(`/api/blogs?id=${id}`)
    // const res = await (axios as any).delete(`/api/blogs/${id}`)
    if (res.data.data.affectedRows) {
      message.success('删除成功')
      toParent && toParent()
    } else {
      message.error('删除失败')
    }
  }

  // 添加数据
  const addBlogsItem = async (values: ArticleItemType) => {
    // 拿到id,新值覆盖旧值
    const res = await axios.post('/api/blogs', values)
    if (res.data.data.affectedRows) {
      message.success('添加成功')
      toParent && toParent()
    } else {
      message.error('添加失败')
    }
  }

  // 更新数据
  const updateBlogsItem = async (values: ArticleItemType) => {
    const res = await axios.put('/api/blogs', { ...record, ...values })

    if (res.data.data.affectedRows) {
      message.success('更新成功')
      toParent && toParent()
    } else {
      message.error('更新失败')
    }
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }

  return (
    <div>
      ArticlePage
      <Button
        onClick={() => {
          // 要在用户点击添加按钮的时候，清空弹出框中的form表单
          // setFieldsValue 设置表单数据
          // 引用类型 指针控制的类型
          form.setFieldsValue({
            title: '',
            content: '',
            createTime: '',
            author: '',
          })
          setDrawerTitle('添加')
          showDrawer()
        }}
      >
        添加数据
      </Button>
      <Drawer
        size="large"
        title={drawerTile}
        placement="right"
        onClose={onClose}
        visible={visible}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="作者"
            name="author"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="创作时间"
            name="createTime"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
      <Table columns={columns} dataSource={tableList} />
    </div>
  )
}

export default ArticlePage
